﻿namespace UserStories.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Transactions;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Security;

    using DotNetOpenAuth.AspNet;

    using Microsoft.Web.WebPages.OAuth;

    using UserStories.Filters;
    using UserStories.Models;

    using WebMatrix.WebData;

    [Authorize]
    //[InitializeSimpleMembership]
    public class AccountController : Controller
    {
        private readonly IProjectsService _projectsService;

        public AccountController() : this(FakeProjectsService.Instance())
        {
            
        }

        public AccountController(IProjectsService projectsService)
        {
            _projectsService = projectsService;
        }

        //
        // GET: /Account/Login
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {           
            if (ModelState.IsValid && _projectsService.IsValidUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                return RedirectToLocal(returnUrl);
            }
            
            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }

        //
        // POST: /Account/LogOff
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login", "Account");
        }


        private ActionResult RedirectToLocal(string returnUrl)
        {
            return this.Url.IsLocalUrl(returnUrl)
                       ? (ActionResult)this.Redirect(returnUrl)
                       : this.RedirectToAction("Index", "Projects");
        }
    }
}
